package com.lb.zookeeper.demo;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @Author lb
 * @Title: ConnectionDemo
 * @Description: TODO
 * @Date 2019/04/04  15:42
 */
public class ConnectionDemo {

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        ZooKeeper zooKeeper = new ZooKeeper("192.168.245.130:2181,192.168.245.131:2181," +
                "192.168.245.132:2181", 4000, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                if (Event.KeeperState.SyncConnected == watchedEvent.getState()){
                    countDownLatch.countDown();
                }
            }
        });
        countDownLatch.await();
//        Thread.sleep(1000);
        System.out.println(zooKeeper.getState());
        //新增节点
        zooKeeper.create("/zk-presistence", "lb".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        Thread.sleep(1000);
        Stat stat = new Stat();
        //得到当前节点的值
        byte[] bytes = zooKeeper.getData("/zk-presistence", null, stat);
        System.out.println(new String(bytes));
        System.out.println(stat.getVersion()+"第一次");
        //修改节点值
        zooKeeper.setData("/zk-presistence", "libin".getBytes(), stat.getVersion());

        byte[] bytes1 = zooKeeper.getData("/zk-presistence", null, stat);
        System.out.println(new String(bytes1));

        System.out.println(stat.getVersion()+"第二次");
        zooKeeper.delete("/zk-presistence", stat.getVersion());

        zooKeeper.close();
//        System.in.read();
    }
}
